from queue import Queue

N = 110
# 定义四种状态
dx, dy = [-1, 0, 1, 0], [0, 1, 0, -1]

def bfs(n, m, g) -> int:
    # 全局状态标记-1代表没有走过
    d = [[-1] * m for _ in range(n)]
    # 0 是初始位置
    d[0][0] = 0
    # 初始化队列
    q = Queue()
    q.put((0, 0))

    while not q.empty():
        t = q.get()

        for i in range(4):
            x, y = t[0] + dx[i], t[1] + dy[i]
            # 判断 x,y 坐标是否溢出，g[x][y] == 0这个位置是否可以走，d[x][y] == -1这个位置没有被走过
            if 0 <= x < n and 0 <= y < m and g[x][y] == 0 and d[x][y] == -1:
                # 表示走到第几步了
                d[x][y] = d[t[0]][t[1]] + 1
                q.put((x, y))

    return d[n - 1][m - 1]

if __name__ == '__main__':
    n, m = map(int, input().split())
    # 读入迷宫数据
    g = [list(map(int, input().split())) for _ in range(n)]
    print(bfs(n, m, g))